import express from 'express';
import router from './routes/index.js'
import config from './config'
import bodyParser from 'body-parser'
import chalk from 'chalk';

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.all('*', (req, res, next) => {
    const {
        origin,
        Origin,
        referer,
        Referer
    } = req.headers;
    const allowOrigin = origin || Origin || referer || Referer || '*';
    res.header("Access-Control-Allow-Origin", allowOrigin);
    //设置*的话，游览器将不会发送cookies，即使你的XHR设置了withCredentials

    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    //表明它允许跨域请求包含Content-Type, Authorization, X-Requested-With头

    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    //simple method 是指 GET, HEAD 或者 POST。所以这三个方法是例外的。
    //猜测Access-Control-Allow-Methods设置的并不是服务端允许请求的方法，而是服务器支持的所有跨域请求的方法。是为了避免浏览次请求的多次'预检'请求。

    //res.header("Access-Control-Allow-Credentials", true); //是否要发送cookie
    //跨域请求想要带上cookies必须在请求头里面加上{crossDomain: true, xhrFields: {withCredentials: true}}设置。

    res.header("X-Powered-By", 'Express');//网站是用何种语言或框架编写
    //res.cookie('testing', 'testing', {httpOnly: true});//testing
    
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});
router(app);
app.use(express.static('./public'));
app.listen(config.port, () => {
    console.log(
        chalk.green( `your application is running at http://localhost:${config.port}`)
    )
})